<?php


namespace app\modules\admin\controllers;


use app\common\services\StaticServices;
use app\models\Calendar;
use yii\base\Exception;
use yii\web\Controller;
use Yii;
use yii\web\Response;

class CalendarController extends Controller {
  public $enableCsrfValidation = false;
  public function actionIndex()
  {
    $p = intval(Yii::$app->request->get('p', 1));
    $calendar_info = Calendar::find();

    $page_size = StaticServices::$page;
    $total_count = $calendar_info->count();
    $total_page = ceil($total_count / $page_size);

    $list = $calendar_info->offset(($p - 1) * $page_size)->orderBy(['create_time' => SORT_DESC])->limit($page_size)->all();
    foreach($list as $k=>$v){
      $list[$k]['history_today'] = mb_substr($v['history_today'],0,33);
      $list[$k]['marketing'] = mb_substr($v['marketing'],0,33);
    }
    return $this->render('index', ['list' => $list, 'p' => $p, 'total_page' => $total_page]);
  }

  public function actionSet()
  {
    $calendar_id = intval(Yii::$app->request->get('id', 0));
    $calendar_info = [];
    if ($calendar_id) {
      $calendar_info = Calendar::find()->where(['id' => $calendar_id])->asArray()->one();
        $calendar_info['history_today'] = preg_replace("/<br\\s*?\/??>/i", "&#10;", $calendar_info['history_today']);
        $calendar_info['marketing'] = preg_replace("/<br\\s*?\/??>/i", "&#10;", $calendar_info['marketing']);

    }

    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $cal_value = trim(Yii::$app->request->post('cal_value', ''));
        $cal_name = trim(Yii::$app->request->post('cal_name', ''));
        $history_today = Yii::$app->request->post('cal_history_today', '');
        $cal_marketing = Yii::$app->request->post('cal_marketing', '');
        $image_url = trim(Yii::$app->request->post('image_url', ''));
        $cal_id = intval(Yii::$app->request->post('cal_id', 0));
        if (mb_strlen($cal_value, 'utf-8') < 1) {
          throw new Exception("请填写日期");
        }
        if (mb_strlen($cal_name, 'utf-8') < 1) {
          throw new Exception("请填写日期标签");
        }
        $res = Calendar::find()->where(['date_value' => $cal_value])->one();

        $calendar_arr = Calendar::find()->where(['id' => $cal_id])->one();
        if ($calendar_arr) {
          $calendar_info = $calendar_arr;
        } else {
          $calendar_info = new Calendar();
          $calendar_info->create_time = time();
        }
        $calendar_info->date_value = $cal_value;
        $calendar_info->data_name = $cal_name;
        $calendar_info->history_today = $history_today;
        $calendar_info->marketing = $cal_marketing;
        if(!empty($image_url)){
          $calendar_info->image_url = $image_url;
        }
        $calendar_info->date_unix = strtotime($cal_value);
        $calendar_info->save(0);

        return ['code' => 200, 'msg' => "操作成功"];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }

    return $this->render('set', ['info' => $calendar_info]);
  }

  public function actionOps()
  {
    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $cal_id = intval(Yii::$app->request->post('cal_id', 0));
        if ($cal_id) {
          Calendar::deleteAll(['id' => $cal_id]);
          return ['code' => 200, 'msg' => "操作成功"];
        }
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }

  public function actionUpload(){
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $upload_name = 'image_url';
    $photo = $_FILES[$upload_name];
    $s = strchr($photo['type'],'/');
    $type = ltrim($s,'/');  // 图片后缀名
    $file = $_FILES[$upload_name]["tmp_name"];//获取的上传的临时文件
    $file_true_name = $_FILES[$upload_name]["name"];//获取上传文件的文件名
    $folderName = date('Ymd');//放进今天日期的文件夹中
    $path = Yii::$app->basePath .'/web/upload/'.$folderName.'/';//存放的路径（不包含文件名）
    $file_name = time().rand(1,1000).'.'.$type;
    if (is_dir($path)){
      if( move_uploaded_file($file ,$path.$file_name)){
        return ['code' => 200, 'msg' => "上传成功", 'data'=>'http://'.$_SERVER['SERVER_NAME'].'/upload/'. $folderName . '/'.$file_name];
      }else{
        return ['code' => -200, 'msg' =>'上传失败'];
      }
    }else{
      $res=mkdir($path,0777,true); //递归创建文件目录
      if ($res){
        chmod($path, 0777);
        if (is_dir($path)){
          if( move_uploaded_file($file ,$path.$file_name)){
            return ['code' => 200, 'msg' => "上传成功",'data'=>'http://'.$_SERVER['SERVER_NAME'].'/upload/'. $folderName . '/'.$file_name];
          }else{
            return ['code' => -200, 'msg' =>'上传失败'];

          }
        }
      }else{
        return ['code' => -200, 'msg' =>'上传失败'];

      }
    }
  }
}